package dao.impl;

import dao.ProductDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import pojo.Product;
import utils.JdbcUtils;
import java.sql.SQLException;
import java.util.List;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.7 下午 15:47
 */
public class ProductDaoimpl implements ProductDao {
    /**
     * 最新商品
     * @return
     */
    @Override
    public List<Product> selectnewProdect() throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from product order by pdate asc limit 9";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }

    /**
     * 热门图片
     * @return
     */
    @Override
    public List<Product> selecthotProdect() throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from product where is_hot order by pdate limit 9";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }

    @Override
    public Product selectProductById(String pid) throws SQLException {

        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from product where pid = ?";
        Product product = qr.query(sql, new BeanHandler<Product>(Product.class), pid);
        return product;
    }

    @Override
    public List<Product> selectProductByPage(int currentPage, int pageSize, String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from product where cid = ? limit ? ,?";
        List<Product> productList = qr.query(sql, new BeanListHandler<Product>(Product.class),
                cid, (currentPage - 1) * pageSize, pageSize);
        return productList;
    }

    @Override
    public int selectTotalCount(String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select count(*) from product where cid = ?";
        String str = (qr.query(sql, new ScalarHandler<>(),cid)).toString();
        int count = Integer.parseInt(str);
        return count;
    }
}
